package pers.xiaojun.boot.common.validation.validator;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import pers.xiaojun.boot.common.validation.ArrayValuable;
import pers.xiaojun.boot.common.validation.constraints.InEnum;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * InEnum 校验器
 *
 * @author xiaojun
 * @since 2025-11-01
 */
public class InEnumValidator implements ConstraintValidator<InEnum, Object> {

    private List<?> list;

    @Override
    public void initialize(InEnum constraintAnnotation) {
        ArrayValuable<?>[] values = constraintAnnotation.value().getEnumConstants();
        if (values.length == 0) {
            list = Collections.emptyList();
        } else {
            list = Arrays.asList(values[0].array());
        }
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext content) {
        if (value == null) {
            return true;
        }
        if (list.contains(value)) {
            return true;
        }
        // 禁用默认的 message
        content.disableDefaultConstraintViolation();
        // 添加自定义的 message
        content.buildConstraintViolationWithTemplate(
                        content.getDefaultConstraintMessageTemplate().replaceAll("\\{value}", list.toString())
                )
                .addConstraintViolation();
        return false;
    }
}
